import { createApp } from "vue";
import App from "./App.vue";
import appUse from "./common/utils/app_use";
import store from "./store";
import moment from "moment";
import isBetween from 'moment/plugin/isBetween';
import duration from 'moment/plugin/duration';
import i18n from '@/locale/index';
import { mainAppRouter, history } from "@/router/index";
import "ant-design-vue/dist/antd.less";
import "animate.css/animate.css";

import "./common/styles/global.css";
import "./common/styles/common.less";

import "./router-path"
import "./common/utils/permission";


moment.extend(isBetween);
moment.extend(duration);
import microApp from "@micro-zoe/micro-app";

// main.js
let app = null
// 👇 将渲染操作放入 mount 函数，子应用初始化时会自动执行
window.mount = () => {
  microApp.start({
    tagName: "micro-app-org", // 标签名称必须以 `micro-app-` 开头
  });
  app = createApp(App)
  appUse(app);
  app.use(i18n);
  app.mount('#app')
}

// 👇 将卸载操作放入 unmount 函数，就是上面步骤2中的卸载函数
window.unmount = () => {
  app.unmount();
  history?.destroy();
  app = null;
}

// 如果不在微前端环境，则直接执行mount渲染
if (!window.__MICRO_APP_ENVIRONMENT__) {
  window.mount()
} else {
  const mainDataListener = (appData) => {
    saveProps(appData);
  };
  const appData = window?.microApp?.getData() || {};
  saveProps(appData);
  window.microApp.addDataListener(mainDataListener);
}

function saveProps(appData) {
  let props = appData?.props || {};
  if (Object.keys(props).length) {
    window.ORGCOMMON_BASE_URL = props.customDomain;
    store.dispatch("SetMainAppProps", props).then((res) => {
      const { token } = res;
      // 取出token到vuex
      if (token) {
        store.dispatch("SetToken", token);
      }
    });
  }
}
